package com.example.fp.cgc.controller

import com.example.fp.cgc.code.logAnno.LogAnno
import com.example.fp.cgc.entity.Apps
import com.example.fp.cgc.entity.DeveloperData
import com.example.fp.cgc.entity.Tags
import com.example.fp.cgc.mapper.AppsMapper
import io.swagger.annotations.ApiOperation
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Lazy
import org.springframework.web.bind.annotation.*
import springfox.documentation.swagger2.annotations.EnableSwagger2


/**
 * @author 蔡
 * @since 2020-01-07
 */
@CrossOrigin
@RestController(value = "apps")
@EnableSwagger2
open class AppsController {
    @Autowired
    @Lazy
    lateinit var appsMapper: AppsMapper

    @LogAnno(operateType = "应用添加")
    @ApiOperation("应用添加")
    @GetMapping("/addApps")
    open fun addApps(apps: Apps) = appsMapper.insert(apps)

    @LogAnno(operateType = "应用列表")
    @ApiOperation("应用列表")
    @PostMapping("/getAppsList")
    open fun getAppsList(): List<Apps> = appsMapper.selectList(null)

    @LogAnno(operateType = "应用更新")
    @ApiOperation("应用更新")
    @PostMapping("/updateApps")
    open fun updateApps(apps: Apps) = appsMapper.updateById(apps)

    @LogAnno(operateType = "应用删除")
    @ApiOperation("应用删除")
    @DeleteMapping("/deleteApps")
    open fun deleteApps(id: Int) = appsMapper.deleteById(id)

    //测试
    @LogAnno(operateType = "查询当前开发者信息")
    @RequestMapping(value = ["/selectDevelop"], method = [RequestMethod.GET])
    open fun selectDevelop(): List<DeveloperData> {
        val developList = appsMapper.getDevelopList()
        return developList
    }

    //测试
    @LogAnno(operateType = "查询当前开发者信息")
    @RequestMapping(value = ["/selectAppsTags"], method = [RequestMethod.GET])
    open fun selectAppsTags(): List<Tags> {
        val tagsList = appsMapper.getAppsTags()
        var tagsMap = linkedMapOf<String, Int>()
        tagsList.forEach { tags ->
            val tagList = tags.split(" ")
            tagList.forEach {t->
                if (tagsMap.containsKey(t)){
                    val num = tagsMap[t]
                    num?.let {
                        tagsMap[t] = it + 1
                    }
                } else {
                    tagsMap[t] = 1
                }
            }
        }
//        val sortList = ArrayList(tagsMap.entries)
//        sortList.sortWith(Comparator { o1, o2->
//            o1.value - o2.value
//        })
//
//        val list = mutableListOf<Tags>()
//        sortList.forEach{
//            list.add(Tags(it.key,it.value))
//        }
//
//        return list
        return tagsMap.entries.map{
            Tags(it.key, it.value)
        }.sortedBy {
            it.value
        }
    }

}